package com.yinp.proapp.base.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.view.View;
import android.view.Window;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

import com.yinp.proapp.R;
import com.yinp.proapp.base.BaseApplication;
import com.yinp.proapp.interfaceOrImplement.UserActivityLifecycleCallbacks;

import java.util.List;

/**
 * 初始activity，所有activity都要继承
 */
public abstract class BaseActivity extends FragmentActivity implements View.OnClickListener {
    public FragmentActivity mActivity;
    public Context mContext;
    public static final String TAG = "yinp_yinp";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //界面间的切换动画
        getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
        Transition enter = TransitionInflater.from(this).inflateTransition(R.transition.exit_animation);
        getWindow().setEnterTransition(enter);//进入
        getWindow().setExitTransition(enter);//退出
        getWindow().setReenterTransition(enter);//用于决定如果当前Activity已经打开过，并且再次打开该Activity时的动画

        mActivity = this;
        mContext = this;

        clearFragmentsBeforeCreate();
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 结束除了当前Activity外的其他Activity
     */
    protected void finishOtherActivities() {
        UserActivityLifecycleCallbacks lifecycleCallbacks = BaseApplication.getInstance().getLifecycleCallbacks();
        if (lifecycleCallbacks == null) {
            finish();
            return;
        }
        List<Activity> activities = lifecycleCallbacks.getActivityList();
        if (activities == null || activities.isEmpty()) {
            finish();
            return;
        }
        for (Activity activity : activities) {
            if (activity != lifecycleCallbacks.current()) {
                activity.finish();
            }
        }
    }

    /**
     * 处理因为Activity重建导致的fragment叠加问题
     */
    public void clearFragmentsBeforeCreate() {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments.size() == 0) {
            return;
        }
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        for (Fragment fragment : fragments) {
            fragmentTransaction.remove(fragment);
        }
        fragmentTransaction.commitNow();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mActivity = null;
        mContext = null;
    }
}
